package org.beetl.support;

import java.util.Map;

import javax.sql.DataSource;

public abstract class JdbcSupport {

 protected JdbcConfigManager jdbcConfigManager;

 public JdbcSupport(JdbcConfigManager jdbcConfigManager) {
  super();
  this.jdbcConfigManager = jdbcConfigManager;
 }

 /** The data sources. */
 Map<String, DataSource> dataSources = new java.util.concurrent.ConcurrentHashMap<String, DataSource>();

 /**
  * Gets the data source.
  *
  * @param jdbcConfig
  *         the jdbc config
  * @return the data source
  */
 public DataSource getDataSource(JdbcConfig jdbcConfig) {
  jdbcConfig.validate();
  if (dataSources.containsKey(jdbcConfig.getId())) {
   return dataSources.get(jdbcConfig.getId());
  }
  JdbcConfig existed = this.jdbcConfigManager.getJdbcConfig(jdbcConfig.getId());
  if (existed == null) {
   this.jdbcConfigManager.putJdbcConfig(jdbcConfig.getId(), jdbcConfig);
  }
  DataSource ds = this.buildDataSource(jdbcConfig);
  this.dataSources.put(jdbcConfig.getId(), ds);
  return ds;
 }

 public DataSource getDataSource(String id) {
  CommonSupport.throwIfNull(id, "id of dataSource not allow null");
  JdbcConfig jdbcConfig = this.jdbcConfigManager.getJdbcConfig(id);
  CommonSupport.throwIfNull(jdbcConfig, "jdbc config with id(" + id + ") not found.");
  return getDataSource(jdbcConfig);
 }

 /**
  * Builds the data source.
  *
  * @param jdbcConfig
  *         the jdbc config
  * @return the data source
  */
 public abstract DataSource buildDataSource(JdbcConfig jdbcConfig);

}
